# 定义一个拦截器（装饰器）
import json

from pip._vendor.requests import Response

import config


def check_hook(func):
    """
    拦截配置，装饰器
    :param func:
    :return:
    """

    def wrapper(self, *args, **kwargs):
        a = False
        if a:
            # 重定向操作
            self.redirect("/test")
            # 统一返状态回码
            # self.write({"state": "200", })
            # 页面渲染
            # self.render("test.html")
            return
        return func(self, *args, **kwargs)

    return wrapper


# 处理刷新页面的请求
def auth_login_redirect(func):
    # 登录验证
    def logical(self, *args, **kwargs):
        # 打印报头
        head_contents = self.request.headers
        print(head_contents)
        # Content-Type: application/x-www-form-urlencoded
        # Connection: keep-alive
        # Accept-Encoding: gzip, deflate
        # Selfheader: CSDN  (自定义的header)
        # Content-Length: 6
        # Cache-Control: no-cache
        # User-Agent: PostmanRuntime/7.19.0
        # Postman-Token: 5c4e1f5c-acc5-4769-ab0d-f20a62d4f8aa
        # Accept: */*
        # Host: 127.0.0.1:8000
        if not self.session['is_login']:
            # 没登录，就让跳到登陆页面
            self.redirect(config.options.get("LOGIN_URL"))
            return
        # 执行post方法或get方法
        func(self, *args, **kwargs)

    return logical


# 处理ajax请求，往往需要返回一段json字符串
def auth_login_json(func):
    def inner(self, *args, **kwargs):
        # if not self.session['is_login']:
        if not self.current_user:
            # 当is_login为False时，没登录
            rep = Response
            # 前端根据这个信息，来确定是否弹出登录注册框
            rep.summary = 'auth failed'
            self.write(json.dumps(rep.__dict__))
            return
        # 执行post方法或get方法
        func(self, *args, **kwargs)

    return inner
